<template>
  <div class="login">
    <h1>后台管理系统</h1>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名 :" prop="username">
        <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密  码 :" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-button type="info" plain @click="login('ruleForm')">登陆</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "login",
  data() {
    //密码正则
    let pass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入你的密码"));
      } else if (value.length >= 4 && value.length <= 16) {
        callback();
      } else {
        callback(new Error("请输入6-16为之间的密码"));
      }
    };
    //用户名正则
    let username = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入你的用户名"));
      } else if (/^[A-z][A-z0-9|.]{4,11}/.test(value)) {
        callback();
      } else {
        callback(new Error("你输入正确的用户名"));
      }
    };
    return {
      ruleForm: {
        pass: "",
        username: ""
      },
      rules: {
        username: [
          {
            validator: username,
            trigger: "blur"
          }
        ],
        pass: [
          {
            validator: pass,
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    //登陆
    login(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          this.$http
            .post("/login_pc/", {
              username: this.ruleForm.username,
              password: this.ruleForm.pass
            })
            .then(e => {
              console.log(e);
              if (e.data.code == -1) {
                this.$message.error(e.data.msg);
              } else {
                this.$message(e.data.msg);
                this.$cookie.set("token", e.data.token);   //cookie中存token
                this.$store.commit('cuntoken',e.data.token)  // vuex传递token 
                this.$router.push('/')
              } 
            });
        } else {
          // 失败
          return false;
        }
      });
    }
  }
};
</script>

<style lang='sass' scopr>
body 
  background-color: #999999
.login 
  width: 500px
  height: 300px
  position: absolute
  border-radius: 10px
  top: 50%
  left: 50%
  transform: translate(-50%, -50%)
  background-color: #dddddd
  box-sizing: border-box
  text-align: center
  padding-right: 30px
.el-button  
  width: 400px
  border-radius: 10px
  margin-left: 75px

</style>